var toPage;
$(function () {
    bankInfoValidation();
    loadBankList();
});

function bankInfoValidation() {
    $('#bankInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',

            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 16,
                    },
                    regexp: {
                        regexp: /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
                        message: '银行名称只能由汉字、字母、数字、横线和下划线组成'
                    }
                }
            },
            province: {
                validators: {
                    notEmpty: {
                        message: '请选择省份'
                    },
                    callback: {
                        message: '请选择省份',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#province'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, city: {
                validators: {
                    notEmpty: {
                        message: '请选择市'
                    },
                    callback: {
                        message: '请选择市',
                        callback: function (value, validator) {
                            if (!getSelectValue($('#city'))) {
                                return false;
                            } else {
                                return true;
                            }
                        }
                    }
                }
            }, address: {
                validators: {
                    notEmpty: {
                        message: '请输入详细地址'
                    },
                }
            }
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        if(!$('#area').val){
            myAlert('提示', '权限区域不能为空');
            return;
        }
        //获取表单实例
        var $form = $(e.target);
        //获取BootstrapValidator实例
        jQuery.support.cors = true;
        var bv = $form.data('bootstrapValidator');
        var formData = new FormData($("#bankInfoForm")[0]);
        compressPicture($('#add_file_hide').prop('files')[0], 100, 100, 0.75, function(blob){
            if(!isNull(blob)){
            formData.append("minLogo",blob);
            }
            $.ajax({
                url: "/sys/org/save",
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                success: function (data) {
                    $('#bankInfoModal').modal('hide');
                    if (data.code == 200) {
                        myAlert("提示", "保存成功", function () {
                            loadBankList(toPage);
                        })
                    } else {
                        myAlert("提示", data.message)
                    }
                },
                error: function (data) {
                    myAlert("提示", "保存失败")
                }
            });
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

$('#bankInfoModal').on('hidden.bs.modal', function () {
    let form = $('#bankInfoForm');
    form.data('bootstrapValidator').destroy();
    // $('#bankInfoForm').data('bootstrapValidator', null);
    bankInfoValidation();
    form[0].reset();//清空表单
    resetForm(form);
});

/*加载银行列表*/
function loadBankList(_pageIndex) {
    $('#bankInfoModal').modal('hide');
    showLoading(LOADING);
    let searchValue = $('#searchValue').val();
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage=pageIndex;
    getJson('/sys/org/list', {
        type: '1',
        searchValue: searchValue,
        pageIndex: pageIndex,
        pageSize: 10
    }, 'GET', function (data) {
        hideLoading();
        let payload = data['payload'];
        $("#page").paging({
            pageNo: pageIndex,
            totalPage: payload['pages'],
            totalSize: payload['total'],
            callback: function (num) {
                loadBankList(num);
            }
        });
        let order = 1 + 10 * (pageIndex - 1);
        for (let item of payload['data']) {
            item['order'] = order++;
        }
        buildTable($('#bank_list'), title, label, payload['data'], function (td, label, item) {
            switch (label) {
                case 'position':
                    let position = item['province'] + item['city'] + item['address'];
                    $(td).text(position);
                    break;
                case 'logo':
                    $(td).empty();
                   if(!isNull(item['logo'])){
                       let img = createElement('img', td);
                       $(img).addClass('img-preview');
                       $(img).attr('src', fileUrl + item['logo']);
                   }
                    break;
                case 'areaDisplay':
                    let areaSet = [];
                    if (item['areaSet']) {
                        for (let area of item['areaSet']) {
                            areaSet.push(area['name']);
                        }
                    }
                    $(td).text(areaSet.join(','));
                    break;
                case 'opera':
                   if(bankInfoOpera){
                       let edit = createElement('a', td);
                       $(edit).addClass('font-p24');
                       $(edit).attr('href', '##');
                       $(edit).click(function () {
                           editBank(item['id']);
                       });
                       let del = createElement('a', td);
                       $(del).addClass('font-p24').addClass('delete-option-btn').addClass('ml-2');
                       $(del).attr('href', '##');
                       $(del).click(function () {
                           deleteBank(item['id']);
                       });
                       let editIcon = createElement('i', edit);
                       $(editIcon).addClass('iconfont').addClass('icon-bianji-');
                       let delIcon = createElement('i', del);
                       $(delIcon).addClass('iconfont').addClass('icon-shanchuicon');
                   }
                    break;
            }
        })
    });
}

/*添加银行信息*/
function addBank() {
    getProvince($('#province'));
    $('#province').find('option').each(function () {
        $(this).removeAttr('selected');
    });
    buildSelect($('#city'));
    $('#img_load_area').attr('src', '../customize/images/icon/image-upload.png');
    $('#address').text('');
    $('#modal_title').text('添加银行');
    getJson('/sys/org/list', null, 'GET', function (data) {
        buildAreaList($('#listGroup1'), data['payload']['data']);
        $('#bankInfoModal').modal();
    });
}

/*修改银行信息*/
function editBank(id) {
    $('#listGroup1').find(':checkbox').each(function () {
        $(this).removeAttr('checked');
    });
    $('#modal_title').text('修改银行信息');
    getJson('/sys/org/info', {"id": id}, 'GET', function (data) {
        getJson('/sys/org/list', null, 'GET', function (data2) {
            let org = data['payload']['data'];
            $('#id').val(org['id']);
            $('#name').val(org['name']);
            getProvince($('#province'), org['province'], $('#city'), org['city']);
            $('#address').text(org['address']);
            if(isNull(org['logo'])){
                $('#img_load_area').attr('src', '../customize/images/icon/image-upload.png');
            }else {
            $('#img_load_area').attr('src', fileUrl + org['logo']);
            }
            buildAreaList($('#listGroup1'), data2['payload']['data'], org['area'].split(","));
            let areaSet = [];
            for (let area of org['areaSet']) {
                areaSet.push(area['name']);
            }
            $('#areaDisplay').val(areaSet.join(','));
            $('#bankInfoModal').modal();
        })
    })

}

/*删除银行信息*/
function deleteBank(e) {
    myConfirm("提示", "您是否要删除此信息", function (res) {
        if (res) {
            getJson('/sys/org/del', {
                id: e
            }, 'GET', function (data) {
                if (data['code'] == 200) {
                    myAlert("提示", "删除成功", function () {
                        loadBankList(toPage);
                    })
                } else {
                    myAlert("提示", data['message'])
                }
            });
        }
    })
}

/* 权限区域多选系列方法 */
//点击加载企业列表
$('#areaDisplay').click(function () {
    $('#listGroup1').slideDown(0);
});

//确认选择勾选企业
function confirmSelection() {
    $('#area').val('');
    $('#areaDisplay').val('');
    var value = [];
    var name = [];
    $.each($('input:checkbox[name=companyList]:checked'), function () {
        value.push($(this).val());
        name.push($(this).attr('eName'))
    });
    $('#area').val(value.join(','));
    $('#areaDisplay').val(name.join(','));
    $('#listGroup1').slideUp(0);
}

//全选
function selectAll() {
    $('input:checkbox[name=companyList]').prop("checked", true);
    confirmSelection();
}

//全不选
function unselectAll() {
    $('input:checkbox[name=companyList]').prop("checked", false);
}

//取消选择企业
function cancelSelection() {
    $('#listGroup1').slideUp(0);
}

/*选择的图片加载到预览区*/
$('#add_file_hide').change(function (e) {
    if(this.files[0].size /1024 /1024 >10){
        myAlert("提示","选择的图片不能超过10M");
        return;
    }
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            $('#img_load_area').attr('src', this.src);
        };
        img.src = _URL.createObjectURL(file);
    }
})
